package com.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.web.jfinal.JFinalCustomController;
import com.web.model.User;
import com.web.util.VerifyCodeUtil;

/**
 * 功能：'/login'对应的controller,处理登录相关的请求
 * @author chenxm
 *
 */
public class LoginController extends JFinalCustomController {
	
	private final Log log = LogFactory.getLog(LoginController.class);
	
	/**
	 * 功能：跳转到login登录界面
	 */
	public void index() {
		if(getSessionAttr("sessionUser") == null) {
			render("/view/login/login.html");
		}else {
			render("/index.html");
		}
	}
	
	/**
	 * 功能：登录验证过程
	 */
	public void loginUser() {
		String loginUserName = getPara("loginUserName");
		String loginPassword = getPara("loginPassword");
		String loginVerifyCode = getPara("loginVerifyCode");
		
		if(loginUserName == null || loginUserName.length() <= 0) {
			setAttr("alert_msg", "用户名不能为空");
			render("/view/login/login.html");
			return;
		}
		
		if(loginPassword == null || loginPassword.length() <= 0) {
			setAttr("alert_msg", "密码不能为空");
			render("/view/login/login.html");
			return;
		}
		
		if(loginVerifyCode == null || loginVerifyCode.length() <= 0) {
			setAttr("alert_msg", "验证码不能为空");
			render("/view/login/login.html");
			return;
		}		
		
		
		//验证校验码
		if(!loginVerifyCode.equalsIgnoreCase(getSession().getAttribute("validStr").toString())) {
			setAttr("alert_msg", "验证码输入错误");
			render("/view/login/login.html");
			return;
		}
		
		//验证用户密码
		 String password = User.dao.getPwdByName(loginUserName);
		 if("".equals(password)) {
			 setAttr("alert_msg", "用户不存在");
			 render("/view/login/login.html");
			return;
		 }else if(!password.equals(loginPassword)) {
			 setAttr("alert_msg", "密码错");
			 render("/view/login/login.html");
			 return;	
		 }else if(password.equals(loginPassword)) {
			 setSessionAttr("sessionUser", loginUserName);
			 //render("/index.html");
			 redirect("/");
			 return;
		 }
		 
	}
	
	/**
	 * 功能：用于登录界面生成验证码
	 * @throws IOException 
	 */
	public void getVerifyCode() throws IOException {
		String validStr = VerifyCodeUtil.createRandomStr(4);
		getSession().setAttribute("validStr", validStr.toUpperCase());//将生产的验证码写入session,待验证登录信息时进行验证
		BufferedImage image = (BufferedImage)VerifyCodeUtil.createImage(validStr);
		getResponse().setContentType("image/jpep");
		ImageIO.write(image, "jpg", getResponse().getOutputStream());
		renderNull();//需指定返回null,否则jfinal会报错
	}
}
